import React, { useEffect, useState,useRef,useContext } from 'react'
import { Table, Button, Modal,Form ,Input} from 'antd'
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { classify,updateClassify,delClassify } from "../../../api/api"


export default function NewsCategory() {
  const [dataSource, setDataSource] = useState([]);
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
        return <b>{id}</b>
      }
    },
    {
      title: '栏目名称',
      dataIndex: 'title',
      onCell: (record) => ({
        record,
        editable: true,
        dataIndex: 'title',
        title: '栏目名称',
        handleSave,
      }),
    },
    {
      title: '操作',
      render: (item) => {
        return (
          <div>
            <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMethod(item)} />
          </div>
        )
      }
    },
  ];
  useEffect(() => {
    const httpRequest = async () => {
      //获取分类列表
      const res=await classify()
      let data=res.data.data;
        data.forEach(item=>{
          if(item.children.length===0){
            return delete item.children
          }
          item.children.forEach(citem=>{
            if(citem.children.length===0){
              return delete citem.children
            }
          })
        })
        setDataSource(data)
    }
    httpRequest()
  }, [])
  const confirmMethod = (item) => {
    Modal.confirm({
      title: '你确定要删除？',
      icon: <ExclamationCircleOutlined />,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deleteMethod(item)
      }
    });
  }
  const deleteMethod = (item) => {
    setDataSource(dataSource.filter(data => data.id !== item.id))
    //删除分类
    delClassify({
      id:item.id
    })
  }

  const EditableContext = React.createContext(null);
  const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };
  
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current.focus();
      }
    }, [editing]);
  
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };
  
    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({ ...record, ...values });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };
  
    let childNode = children;
  
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
  
    return <td {...restProps}>{childNode}</td>;
  };
  const handleSave = (row) => {
    setDataSource(dataSource.map(item=>{
      if(item.id===row.id){
        return {
          id:row.id,
          title:row.title
        }
      }
      return item
    }));
    //修改分类
    updateClassify({
      id:row.id,
      title:row.title
    })
  };
  return (
    <div>
      <Table dataSource={dataSource} columns={columns} rowKey={(item) => item.id} pagination={{
        pageSize: 5,
        pageSizeOptions:[]
      }} components={{
        body: {
          row: EditableRow,
          cell: EditableCell,
        },
      }}/>
    </div>
  )
}
